<template>
  <div class="order-confirm">
    <h2>立即购买</h2>
    <el-card>
      <!-- 菜品信息 -->
      <div class="dish-info">
        <h3>菜品信息</h3>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-image :src="dish.imageUrl" fit="cover" class="dish-image"/>
          </el-col>
          <el-col :span="18">
            <p><span class="label">菜品名称：</span>{{ dish.name }}</p>
            <p><span class="label">菜品价格：</span>¥ {{ dish.price.toFixed(2) }}</p>
            <p><span class="label">菜品描述：</span>{{ dish.description }}</p>
          </el-col>
        </el-row>
      </div>

      <!-- 配送地址 -->
      <div class="address-info">
        <h3>选择配送地址</h3>
        <!-- 没有地址时的提示 -->
        <div v-if="addresses.length === 0" class="no-address">
          <p>您还没有添加收货地址，请先添加地址。</p>
          <el-button type="primary" @click="goToAddressPage">添加收货地址</el-button>
        </div>

        <!-- 有地址时的选择框 -->
        <el-select
            v-else
            v-model="selectedAddressId"
            placeholder="请选择配送地址"
            class="address-select"
        >
          <el-option
              v-for="address in addresses"
              :key="address.addressId"
              :label="formatAddressLabel(address)"
              :value="address.addressId"
          />
        </el-select>

        <!-- 选中地址的详细信息 -->
        <div v-if="selectedAddressId" class="selected-address-details">
          <p><span class="label">收货人姓名：</span>{{ selectedAddress?.username }}</p>
          <p><span class="label">收货人手机号：</span>{{ selectedAddress?.phone }}</p>
          <p><span class="label">收货地址：</span>{{ selectedAddress?.addressDetail }}</p>
        </div>
      </div>

      <!-- 购买数量 -->
      <div class="quantity-info">
        <h3>购买数量</h3>
        <p><span class="label">数量：</span></p>
        <el-input-number v-model="quantity" :min="1" :max="10"/>
      </div>

      <!-- 总金额 -->
      <div class="total-price">
        <h3>总金额</h3>
        <p><span class="label">总价：</span>¥ {{ totalPrice.toFixed(2) }}</p>
      </div>

      <!-- 立即支付按钮 -->
      <div class="actions">
        <el-button type="primary" @click="handlePay">立即支付</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {ref, computed, onMounted} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import {apiGet, apiPost} from '@/utils/api';
import {useUserStore} from '@/store/modules/user';
import type {Address, Dish} from '@/types/entity';
import {sessionStorage} from "@/utils/storage";

const router = useRouter();
const userStore = useUserStore();

// 从路由参数中获取 dishId
const dishId = ref<number>(Number(router.currentRoute.value.query.dishId));

// 检查 dishId 是否有效
if (isNaN(dishId.value)) {
  ElMessage.error('菜品ID无效');
  router.push('/error'); // 跳转到错误页面
}

// 菜品信息
const dish = ref<Dish>({
  dishId: 0,
  name: '',
  description: '',
  price: 0,
  stock: 0,
  imageUrl: '',
  status: 0,
  createdAt: '',
  updatedAt: '',
  dishCategoryId: 0,
  restaurantId: 0,
  restaurantName: '',
  dishCategoryName: '',
  address: '',
  phone: '',
});

// 配送地址列表
const addresses = ref<Address[]>([]);
const selectedAddressId = ref<number | null>(null);

// 当前选中的地址
const selectedAddress = computed(() => {
  return addresses.value.find(addr => addr.addressId === selectedAddressId.value);
});

// 购买数量
const quantity = ref(1);

// 计算总金额
const totalPrice = computed(() => {
  return dish.value.price * quantity.value;
});

// 获取菜品信息
const fetchDishInfo = async () => {
  const {data} = await apiGet(`/dish/findAll`, {
    page: 1,
    limit: 10,
    dishId: dishId.value,
  });
  let dataOne = data.data[0];
  if (dataOne) {
    dish.value = {
      dishId: dataOne.dishId,
      name: dataOne.name,
      description: dataOne.description,
      price: dataOne.price,
      stock: dataOne.stock,
      imageUrl: dataOne.imageUrl,
      status: dataOne.status,
      createdAt: dataOne.createdAt,
      updatedAt: dataOne.updatedAt,
      dishCategoryId: dataOne.dishCategoryId,
      restaurantId: dataOne.restaurantId,
      restaurantName: dataOne.restaurantName,
      dishCategoryName: dataOne.dishCategoryName,
      address: dataOne.address,
      phone: dataOne.phone,
    };
  }
};

// 获取用户配送地址
const fetchUserAddresses = async () => {
  const {data} = await apiGet('/address/getAllByUserId', {userId: userStore.id});
  addresses.value = data;

  // 默认选择默认地址
  const defaultAddress = data.find((addr: Address) => addr.isDefault === 1);
  if (defaultAddress) {
    selectedAddressId.value = defaultAddress.addressId;
  } else if (data.length > 0) {
    selectedAddressId.value = data[0].addressId; // 如果没有默认地址，选择第一个地址
  }
};

// 跳转到收货地址管理页面
const goToAddressPage = () => {
  router.push('/user/address');
};

// 处理立即支付
const handlePay = async () => {
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择配送地址');
    return;
  }
  let order = {
    dishId: dish.value.dishId,
    quantity: quantity.value,
    addressId: selectedAddressId.value,
    paymentMethod: 1,
    orderStatus: 1,
  };
  // 调用后端接口，生成支付订单
  const response = await fetch(`${import.meta.env.VITE_SERVE}alipay/pay`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'token': sessionStorage.get('token') || '', // 传递 token
    },
    body: JSON.stringify(order),
  });
  if (response.ok) {
    // 获取返回的 HTML 表单
    const formHtml = await response.text();

    // 将表单插入到页面中并自动提交
    const div = document.createElement('div');
    div.innerHTML = formHtml;
    document.body.appendChild(div);
    document.forms[0].submit(); // 自动提交表单
  } else {
    ElMessage.error('支付失败');
  }
};

// 格式化地址显示
const formatAddressLabel = (address: Address) => {
  return `${address.username} | ${address.phone} | ${address.addressDetail}`;
};

// 初始化时获取数据
onMounted(() => {
  if (!isNaN(dishId.value)) {
    fetchDishInfo();
    fetchUserAddresses();
  }
});
</script>

<style scoped>
.order-confirm {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.dish-info {
  margin-bottom: 20px;
}

.dish-image {
  width: 100%;
  height: 150px;
  border-radius: 8px;
}

.label {
  font-weight: bold;
  color: #333;
}

.dish-info p,
.selected-address-details p,
.quantity-info p,
.total-price p {
  margin: 8px 0;
  font-size: 14px;
  color: #666;
}

.address-info {
  margin-bottom: 20px;
}

.no-address {
  text-align: center;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.no-address p {
  margin-bottom: 10px;
  color: #666;
}

.address-select {
  width: 100%;
  margin-bottom: 20px;
}

.selected-address-details {
  margin-top: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.quantity-info {
  margin-bottom: 20px;
}

.total-price {
  margin-bottom: 20px;
}

.total-price h3 {
  font-size: 18px;
  font-weight: bold;
}

.total-price p {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
}

.actions {
  text-align: right;
}
</style>